package cn.jiyun.controller;


import cn.jiyun.GoodOpenFeign;
import cn.jiyun.SettledOpenFeign;
import cn.jiyun.common.config.Result;
import cn.jiyun.entity.*;
import cn.jiyun.service.IXmOrderService;
import cn.jiyun.service.IXmOrderGoodslistService;
import cn.jiyun.service.IXmRefundService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-11-25
 */
@RestController
@RequestMapping("/xm-trade/order")
public class OrderController {
    @Autowired
    private IXmOrderService orderService;
    @Autowired
    private IXmOrderGoodslistService xmOrderGoodslistService;
    @Autowired
    private SettledOpenFeign settledOpenFeign;
    @Autowired
    private IXmRefundService xmRefundService;
    @Autowired
    private GoodOpenFeign goodOpenFeign;

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyId}")
    private String keyid;
    @Value("${aliyun.keySecret}")
    private String keysecret;
    @Value("${aliyun.bucketName}")
    private String buncket;

    @RequestMapping("saverefund")
    public Result saverefund(@RequestBody XmRefund xmRefund){
        XmOrder byId = orderService.getById(xmRefund.getOid());
        byId.setIsRefunded(1);
        byId.setRefundStatus(1);
        orderService.updateById(byId);
        System.out.println("------------------"+xmRefund);
        xmRefund.setCreatetime(LocalDateTime.now());
        xmRefundService.save(xmRefund);
        return Result.ok();
    }

    @RequestMapping("updatebyid")
    public Result updatebyid(Integer id){
        System.out.println("------------------"+id);
        xmOrderGoodslistService.remove(new LambdaQueryWrapper<XmOrderGoodslist>().eq(XmOrderGoodslist::getOid,id));
        orderService.removeById(id);
        return Result.ok("取消订单成功！");
    }

    @RequestMapping("/save")
    public Result save(@RequestBody XmOrder xmOrder){
//        创建时间，付款时间，预计送达时间
        xmOrder.setCreationTime(LocalDateTime.now());
        xmOrder.setPaymentTime(LocalDateTime.now());
        LocalDateTime now = LocalDateTime.now();
        // 在当前时间基础上加20分钟
        LocalDateTime expectedTime = now.plus(20, ChronoUnit.MINUTES);
        // 将加20分钟后的时间存入xmOrder的setExpectedDeliveryTime方法
        xmOrder.setExpectedDeliveryTime(expectedTime);
        int a=0;
        for (XmOrderGoodslist xl : xmOrder.getXmOrderGoodslists()) {
            a=a+xl.getNumed();
        }
//        xmOrder.set
        System.out.println("保存订单"+xmOrder);
        orderService.save(xmOrder);
        Integer id = xmOrder.getId();
        System.out.println("保存订单id"+id);
        List<XmOrderGoodslist> l = xmOrder.getXmOrderGoodslists();
        System.out.println("保存订单商品"+l);


        for (XmOrderGoodslist xl : l) {
            xl.setOid(id);
            GoodsList byId = goodOpenFeign.findbyid2(xl.getGid());
            byId.setInventory(byId.getInventory()-xl.getNumed());
            byId.setMonthlysales(byId.getMonthlysales()+xl.getNumed());
            System.out.println("111");
            goodOpenFeign.update2(byId);
            System.out.println("222");
            xmOrderGoodslistService.save(xl);
            System.out.println("333");
        }
        return Result.ok();
    }

    @RequestMapping("fileUpload")
    public String fileUpload(MultipartFile file) {
        String url="";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        try {
            // 创建PutObjectRequest对象。
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String replace = UUID.randomUUID().toString().replace("-", "");
            originalFilename = replace+originalFilename;
            String time = new DateTime().toString("yyyy/MM/dd");
            originalFilename = time+"/"+originalFilename;

            PutObjectResult putObjectResult = ossClient.putObject(buncket, originalFilename, inputStream);

            url="https://"+buncket+"."+endpoint+"/"+originalFilename;
        } catch (Exception ce) {
            System.out.println("上传异常--");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }

    //    查询所有商店
    @RequestMapping("findshop")
    public List<XmSettled> findshop() {
        List<XmSettled> list = settledOpenFeign.findAllClient();
        return list;
    }

    @RequestMapping("findPage")
    public Result findPage(Integer current, Integer pageSize, @RequestBody XmOrder order) {
        Page<XmOrder> orderPage = new Page<>(current, pageSize);
        LambdaQueryWrapper<XmOrder> qw = new LambdaQueryWrapper<>();
//        qw.eq(XmOrder::getIsRefunded,0);
        if (order.getTransactionId() != null && order.getTransactionId() != "") {
            qw.like(XmOrder::getTransactionId, order.getTransactionId());
        }
        if (order.getCustomerNickname()!= null && order.getCustomerNickname()!= ""){
            qw.eq(XmOrder::getCustomerNickname, order.getCustomerNickname());
        }
        if (order.getOrderStatus()!= null){
            qw.eq(XmOrder::getOrderStatus, order.getOrderStatus());
        }
        if (order.getSid() != null) {
            qw.eq(XmOrder::getSid, order.getSid());
        }
        if (order.getCustomerNickname() != null && order.getCustomerNickname() != "") {
            qw.like(XmOrder::getCustomerNickname, order.getCustomerNickname());
        }
        if (order.getName() != null && order.getName() != "") {
            qw.like(XmOrder::getName, order.getName());
        }
        if (order.getTel() != null && order.getTel() != "") {
            qw.eq(XmOrder::getBuyerPhone, order.getTel()).or().eq(XmOrder::getReservedPhone, order.getTel());
        }
        if (order.getOrderType() != null && order.getOrderType() != "") {
            qw.eq(XmOrder::getOrderType, order.getOrderType());
        }
        if (order.getStatus() != null) {
            qw.eq(XmOrder::getStatus, order.getStatus());
        }
        if (order.getZtime() != null) {
            LocalDateTime now = LocalDateTime.now();
            int mo = 90;
            if (order.getZtime() == 1) {
                qw.apply("ABS(DATEDIFF({0}, creation_time)) <= {1}", now, mo);
            }
            if (order.getZtime() == 2) {
                qw.apply("YEAR(creation_time)=YEAR(CURRENT_DATE)");
            }
            if (order.getZtime() == 3) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2022");
            }
            if (order.getZtime() == 4) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2021");
            }
            if (order.getZtime() == 5) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2020");
            }
            if (order.getZtime() == 6) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')<2020");
            }
        }
        qw.orderByDesc(XmOrder::getCreationTime);
        Page<XmOrder> page = orderService.page(orderPage, qw);
        System.out.println(page);
        List<XmOrder> records = page.getRecords();
        for (XmOrder record : records) {
//            商店信息
            List<XmSettled> findshop = findshop();
            for (XmSettled xmSettled : findshop) {
                if (record.getSid().equals(xmSettled.getId())) {
                    record.setShopname(xmSettled.getName());
                    record.setShoptel(xmSettled.getTel());
                    record.setShopregion(xmSettled.getAddress());
                    record.setShopaddress(xmSettled.getDetailed());
                }
            }
//            中间表购物的信息
            List<XmOrderGoodslist> list = xmOrderGoodslistService.list(new LambdaQueryWrapper<XmOrderGoodslist>().eq(XmOrderGoodslist::getOid, record.getId()));
            record.setGoods(list);
        }
        return Result.ok(page);
    }

    @RequestMapping("findPage2")
    public Result findPage2(Integer current, Integer pageSize, @RequestBody XmOrder order) {
        Page<XmOrder> orderPage = new Page<>(current, pageSize);
        LambdaQueryWrapper<XmOrder> qw = new LambdaQueryWrapper<>();
        qw.eq(XmOrder::getIsRefunded,1);
        if (order.getTransactionId() != null && order.getTransactionId() != "") {
            qw.like(XmOrder::getTransactionId, order.getTransactionId());
        }
        if (order.getSid() != null) {
            qw.eq(XmOrder::getSid, order.getSid());
        }
        if (order.getCustomerNickname() != null && order.getCustomerNickname() != "") {
            qw.like(XmOrder::getCustomerNickname, order.getCustomerNickname());
        }
        if (order.getName() != null && order.getName() != "") {
            qw.like(XmOrder::getName, order.getName());
        }
        if (order.getTel() != null && order.getTel() != "") {
            qw.eq(XmOrder::getBuyerPhone, order.getTel()).or().eq(XmOrder::getReservedPhone, order.getTel());
        }
        if (order.getOrderType() != null && order.getOrderType() != "") {
            qw.eq(XmOrder::getOrderType, order.getOrderType());
        }
        if (order.getStatus() != null) {
            qw.eq(XmOrder::getStatus, order.getStatus());
        }
        if (order.getZtime() != null) {
            LocalDateTime now = LocalDateTime.now();
            int mo = 90;
            if (order.getZtime() == 1) {
                qw.apply("ABS(DATEDIFF({0}, creation_time)) <= {1}", now, mo);
            }
            if (order.getZtime() == 2) {
                qw.apply("YEAR(creation_time)=YEAR(CURRENT_DATE)");
            }
            if (order.getZtime() == 3) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2022");
            }
            if (order.getZtime() == 4) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2021");
            }
            if (order.getZtime() == 5) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')=2020");
            }
            if (order.getZtime() == 6) {
                qw.apply("DATE_FORMAT(creation_time,'%Y')<2020");
            }
        }
        Page<XmOrder> page = orderService.page(orderPage, qw);
        System.out.println(page);
        List<XmOrder> records = page.getRecords();
        for (XmOrder record : records) {
//            商店信息
            List<XmSettled> findshop = findshop();
            for (XmSettled xmSettled : findshop) {
                if (record.getSid().equals(xmSettled.getId())) {
                    record.setShopname(xmSettled.getName());
                    record.setShoptel(xmSettled.getTel());
                    record.setShopregion(xmSettled.getAddress());
                    record.setShopaddress(xmSettled.getDetailed());
                }
            }
//            退款交流信息
            List<XmRefund> list1 = xmRefundService.list(new LambdaQueryWrapper<XmRefund>().eq(XmRefund::getOid, record.getId()));
            record.setXmRefunds(list1);
//            中间表购物的信息
            List<XmOrderGoodslist> list = xmOrderGoodslistService.list(new LambdaQueryWrapper<XmOrderGoodslist>().eq(XmOrderGoodslist::getOid, record.getId()));
            record.setGoods(list);
        }
        return Result.ok(page);
    }


    @RequestMapping("findAllOrder")
    public Result findAllOrder() {
        Integer num=orderService.findAllOrder();
        return Result.ok(num);
    }

    @RequestMapping("findAllOrder2")
    public Result findAllOrder2() {
        Integer num=orderService.findAllOrder2();
        return Result.ok(num);
    }
}
